//
//  YWHomeViewController.m
//  baibuyewu
//
//  Created by 陈炳桦 on 15/10/26.
//  Copyright © 2015年 陈炳桦. All rights reserved.
//

#import "YWHomeViewController.h"
#import "FPPopoverController.h"
#import "YWMenuViewController.h"
#import "YWInputRecordViewController.h"
#import "YWSettingViewController.h"
#import "YWFeedbackViewController.h"
#import "UPStackMenu.h"
#import "YWInputMerchantViewController.h"
#import "YWReleaseDemandViewController.h"
#import "YWMyReleaseViewController.h"
#import "MJRefresh.h"
#import "MJExtension.h"
#import "AFNetworking.h"
#import "YWBuyerDemand.h"
#import "YWBuyerDemandCell.h"
#import "YWNetwork.h"
#import "YWDemandDetailViewController.h"
#import "YWLoginViewController.h"
#import "YWNavigationController.h"
#import "AppDelegate.h"


@interface YWHomeViewController () <UPStackMenuDelegate>

// 弹出菜单
@property (nonatomic,strong) FPPopoverController *popover;

// 右下角按钮
@property (nonatomic,strong) UIView *contentView;

// 右下角弹出菜单
@property (nonatomic,strong)  UPStackMenu *stack;

// YWBuyerDemand数组
@property (nonatomic,strong) NSMutableArray *buyerDemands;

// 自定义蒙版
@property (nonatomic,strong) UIView *coverView;

// 当前页码
@property (nonatomic, assign) NSInteger page;

@end

@implementation YWHomeViewController

static NSString * const ID = @"Cell";


#pragma mark - 懒加载
- (FPPopoverController *)popover{
    if (_popover == nil) {
        // 弹出菜单的内容控制器
        YWMenuViewController *controller = [[YWMenuViewController alloc] init];
        
        FPPopoverController *popover = [[FPPopoverController alloc] initWithViewController:controller];
    
        popover.border = NO;
        popover.tint = FPPopoverWhiteTint;
        popover.contentSize = CGSizeMake(160,170);
        
         _popover = popover;

    }
    
    return _popover;
}

- (NSMutableArray *)buyerDemands{
    if (_buyerDemands == nil) {
        _buyerDemands = [NSMutableArray array];
    }
    return _buyerDemands;
}

- (UIView *)coverView{
    if (_coverView == nil) {
        _coverView = [[UIView alloc] init];
        _coverView.frame = CGRectMake(0, 0, BBScreenW, BBScreenH);
        
        _coverView.backgroundColor = [UIColor blackColor];
        _coverView.alpha = 0.6;
        
        _coverView.hidden = YES;
        
        // 蒙版点击
        [_coverView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(coverViewClick)]];
        
        [self.view insertSubview:_coverView aboveSubview:self.collectionView];

    }
    
    return _coverView;
}

- (void)coverViewClick{
    // 关闭右下角菜单
    [self.stack closeStack];
}

- (instancetype)init
{
    // 流水布局对象,设置cell的尺寸和位置
    UICollectionViewFlowLayout *layout  = [[UICollectionViewFlowLayout alloc] init];
    
    // 每行cell的个数
    NSInteger colNums = 3;
    // 统一的间距
    CGFloat spacing = 10;
    // cell的宽度 为了适配6plus 把下面的1改成1.5
    CGFloat cellW = (BBScreenW - (colNums + 1.5) * spacing) / colNums;
    // cell的高度
    CGFloat cellH = cellW * 1.6;
    
    // 设置cell的尺寸
    layout.itemSize = CGSizeMake(cellW, cellH);
    // 设置cell之间间距
    layout.minimumInteritemSpacing = spacing;
    // 设置行距
    layout.minimumLineSpacing = spacing;
    // 设置每一组的内间距
    layout.sectionInset = UIEdgeInsetsMake(spacing, spacing, spacing, spacing);
    
    return  [super initWithCollectionViewLayout:layout];
}


- (void)viewDidLoad {
    [super viewDidLoad];

    // 初始化设置
    [self setUp];

    // 设置底部菜单
    [self setUpButtomMenu];
    
    // 设置上拉刷新下拉加载
    [self setupRefresh];
}

- (void)setUp{
    self.navigationItem.title = @"百布业务";
    
    self.collectionView.backgroundColor =  BBRGBColor(234, 236, 238);
    
    // 注册cell
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([YWBuyerDemandCell class]) bundle:nil] forCellWithReuseIdentifier:ID];
    
    
    UIButton *button = [[UIButton alloc] init];
    [button setTitle:@"更多" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [button sizeToFit];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    
    // 监听通知
    // 注册广播图片控件点击通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(selectItem:) name:@"YWMenuViewControllerSelectItem" object:nil];
}

- (void)setupRefresh{
    // 下拉刷新
    self.collectionView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewBuyerDemand)];
    [self.collectionView.header beginRefreshing];
    
    // 上拉加载
    self.collectionView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreBuyerDemand)];
}

- (void)loadNewBuyerDemand{
    
    // 上拉结束
    [self.collectionView.footer endRefreshing];
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"pageNum"] = @0;
    parameters[@"numPerPage"] = @40;
   
    [YWNetwork selectBuyerDemandWithParameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        // 字典数组 -> 模型数组
        NSMutableArray *array = [YWBuyerDemand objectArrayWithKeyValuesArray:responseObject[@"buyerDemandList"]];
        self.buyerDemands = array;
        
        [self.collectionView reloadData];
        
        // 结束刷新
        [self.collectionView.header endRefreshing];
        
        // 清空页码
        self.page = 0;
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [self.collectionView.header endRefreshing];
    }];
    
}

- (void)loadMoreBuyerDemand{
    // 下拉结束
    [self.collectionView.header endRefreshing];
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"numPerPage"] = @40;
    NSInteger page = self.page + 1;
    parameters[@"pageNum"] = @(page);
    
    [YWNetwork selectBuyerDemandWithParameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        [self.collectionView.header endRefreshing];
        
        // 字典数组 -> 模型数组
        NSMutableArray *newdamands = [YWBuyerDemand objectArrayWithKeyValuesArray:responseObject[@"buyerDemandList"]];
        [self.buyerDemands addObjectsFromArray:newdamands];
        
        [self.collectionView reloadData];
        
        // 结束刷新
        [self.collectionView.footer endRefreshing];
        // 设置页码
        self.page = page;
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [self.collectionView.header endRefreshing];
    }];

}


- (void)setUpButtomMenu{
    
    // 设置按钮
    _contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];
    [_contentView setBackgroundColor:BBRGBColor(85, 26, 175)];
    [_contentView.layer setCornerRadius:30.];
    UIImageView *icon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"cross"]];
    [icon setContentMode:UIViewContentModeScaleAspectFit];
    [icon setFrame:CGRectInset(_contentView.frame, 20, 20)];
    [_contentView addSubview:icon];
    
    _stack = [[UPStackMenu alloc] initWithContentView:_contentView];
    [_stack setCenter:CGPointMake(BBScreenW - 50, BBScreenH - 120)];
    [_stack setDelegate:self];
    
    // 设置弹出内容
    UPStackMenuItem *squareItem = [[UPStackMenuItem alloc] initWithImage:[UIImage imageNamed:@"ic_action_receipt"] highlightedImage:nil title:@"我的发布"];
    UPStackMenuItem *circleItem = [[UPStackMenuItem alloc] initWithImage:[UIImage imageNamed:@"ic_av_playlist_add"] highlightedImage:nil title:@"发布需求"];
    UPStackMenuItem *triangleItem = [[UPStackMenuItem alloc] initWithImage:[UIImage imageNamed:@"ic_social_person_add"] highlightedImage:nil title:@"录入商户"];
    NSMutableArray *items = [[NSMutableArray alloc] initWithObjects:squareItem, circleItem, triangleItem, nil];
    [items enumerateObjectsUsingBlock:^(UPStackMenuItem *item, NSUInteger idx, BOOL *stop) {
        [item setTitleColor:[UIColor whiteColor]];
    }];
    
    
    
    [_stack setAnimationType:UPStackMenuAnimationType_progressive];
    [_stack setStackPosition:UPStackMenuStackPosition_up];
    [_stack setOpenAnimationDuration:.4];
    [_stack setCloseAnimationDuration:.4];
    [items enumerateObjectsUsingBlock:^(UPStackMenuItem *item, NSUInteger idx, BOOL *stop) {
        [item setLabelPosition:UPStackMenuItemLabelPosition_left];
    }];
    
    [_stack addItems:items];
    [self.view addSubview:_stack];
}

- (void)setStackIconClosed:(BOOL)closed
{
    UIImageView *icon = [[self.contentView subviews] objectAtIndex:0];
    float angle = closed ? 0 : (M_PI * (135) / 180.0);
    [UIView animateWithDuration:0.3 animations:^{
        [icon.layer setAffineTransform:CGAffineTransformRotate(CGAffineTransformIdentity, angle)];
    }];
}


#pragma mark - UPStackMenuDelegate
- (void)stackMenuWillOpen:(UPStackMenu *)menu
{
    // 显示蒙版
    self.coverView.hidden = NO;
    
    if([[self.contentView subviews] count] == 0)
        return;
    
    [self setStackIconClosed:NO];
}

- (void)stackMenuWillClose:(UPStackMenu *)menu
{
    // 隐藏蒙版
    self.coverView.hidden = YES;
    
    if([[self.contentView subviews] count] == 0)
        return;
    
    [self setStackIconClosed:YES];
}

- (void)stackMenu:(UPStackMenu *)menu didTouchItem:(UPStackMenuItem *)item atIndex:(NSUInteger)index
{
    //录入商户
    if ([item.title isEqualToString:@"录入商户"]) {
        
        YWInputMerchantViewController *inputVC = [[YWInputMerchantViewController alloc] init];
        [self.navigationController pushViewController:inputVC animated:YES];
        
    }else if ([item.title isEqualToString:@"发布需求"]){
        
        YWReleaseDemandViewController *releaseVC = [[YWReleaseDemandViewController alloc] init];
        [self.navigationController pushViewController:releaseVC animated:YES];
        
    }else if ([item.title isEqualToString:@"我的发布"]){
        
        YWMyReleaseViewController *myReleaseVC = [[YWMyReleaseViewController alloc] init];
        [self.navigationController pushViewController:myReleaseVC animated:YES];

    }
    
    [self.stack closeStack];
}

// 弹出菜单监听方法
- (void)selectItem:(NSNotification *)notification{
    
    [self.popover dismissPopoverAnimated:YES];
    
    NSString *text = (NSString *)notification.object;
    
   
    if ([text isEqualToString:@"商户录入记录"]) {
        YWInputRecordViewController *irVC = [[YWInputRecordViewController alloc] init];
        [self.navigationController pushViewController:irVC animated:YES];
    }else if([text isEqualToString:@"应用设置"]){
        YWSettingViewController *settingVC = [[YWSettingViewController alloc] init];
        [self.navigationController pushViewController:settingVC animated:YES];
    }else if([text isEqualToString:@"退出登录"]){
        
        // 弹出actionSheet
        UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"确定要退出?" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"退出" otherButtonTitles:nil, nil];
        
        [sheet showInView:self.view];
    }
    
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) { // 点击了退出,返回登录界面
        
        YWLoginViewController  *loginVC = [[YWLoginViewController alloc] init];
        YWNavigationController *nav = [[YWNavigationController alloc] initWithRootViewController:loginVC];

        AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        delegate.window.rootViewController = nav;
        
        // 清空AccessToken
        YWUserInfo *userInfo = [YWUserInfo sharedUseInfo];
        userInfo.accessToken = nil;
        
    }
    
    
}


#pragma mark - 右上角按钮
- (void)btnClick:(UIButton *)button{
    
    [self.popover presentPopoverFromView:button];
}



#pragma mark -- UICollectionViewDataSource
//定义展示的UICollectionViewCell的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.buyerDemands.count;
}

//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
   YWBuyerDemandCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    
    
    cell.buyerDemand = self.buyerDemands[indexPath.item];

    return cell;
}

#pragma mark -- UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    YWDemandDetailViewController *ddVC = [[YWDemandDetailViewController alloc] init];
    
    ddVC.buyerDemand = self.buyerDemands[indexPath.item];
    
    [self.navigationController pushViewController:ddVC animated:YES];
}

- (void)dealloc{
    // 移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


@end
